package com.aiyige.page.publish.learnvideo;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.eventbus.EventEditLearnVideoFinish;
import com.aiyige.page.player.PlayerInfo;
import com.aiyige.page.publish.learnvideo.adapter.PublishLearnVideoAdapter;
import com.aiyige.page.publish.learnvideo.model.PublishLearnVideoFormModel;
import com.aiyige.page.publish.learnvideo.model.PublishLearnVideoItem;
import com.aiyige.page.publish.selectvideocover.SelectVideoCoverPage;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.utils.CancelEditDialogUtil;
import com.aiyige.utils.FileUtil;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.VideoUtil;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = ARouterConfig.PublishLearnVideoPage, extras = ARouterConfig.EXTRA_NEED_LOGIN | ARouterConfig.EXTRA_NEED_BINDPHONE)
public class PublishLearnVideoPage extends AppCompatActivity {
    public static final String TAG = PublishLearnVideoPage.class.getSimpleName();
    public static final int REQUEST_CODE_SELECT_VIDEO_COVER = 1;
    public static final int REQUEST_CODE_SELECT_VIDEO = 2;
    public static final int REQUEST_CODE_NEXT = 3;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.containerLayout)
    View containerLayout;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    Button titleActionBtn;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.addBtn)
    Button addBtn;
    PublishLearnVideoAdapter publishLearnVideoAdapter;
    EditPublishLearnVideoItemBottomDialog editPublishLearnVideoItemBottomDialog;
    int currentPosition = 0;
    @Autowired
    PublishLearnVideoFormModel formModel = null;
    boolean edit = false;
    TrackEvent trackEvent = new TrackEvent();
    boolean createAndFirstEnter = false;

    @Override
    protected void onPause() {
        containerLayout.requestFocus();
        super.onPause();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_publish_learn_video);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (formModel == null) {
            ToastX.show(R.string.unknown_error);
            super.finish();
            return;
        }

        containerLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightDiff = containerLayout.getRootView().getHeight() - containerLayout.getHeight();
                if (heightDiff > UIHelper.dip2px(200)) { // if more than 200 dp, it's probably a keyboard...
                    addBtn.setVisibility(View.GONE);
                } else {
                    addBtn.setVisibility(View.VISIBLE);
                    containerLayout.requestFocus();
                }
            }
        });
        publishLearnVideoAdapter = new PublishLearnVideoAdapter();
        publishLearnVideoAdapter.setCallback(new PublishLearnVideoAdapter.Callback() {
            @Override
            public void inputTitle(String title) {
                if (edit) {
                    Map<String, String> attrs = new HashMap<>();
                    attrs.put("action_type", "3");
                    trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_MOD_SUB_VIDEO_ACT, TrackEvent.LEARN_VIDEO_MOD_SUB_VIDEO_ACT_LABEL, attrs, true);
                }
                if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
                    Map<String, String> attrs = new HashMap<>();
                    attrs.put("action_type", "3");
                    trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_MOD_SUB_ACT_EDIT, TrackEvent.LEARN_VIDEO_MOD_SUB_ACT_EDIT_LABEL, attrs, true);
                }
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setItemAnimator(null);
        publishLearnVideoAdapter.bindToRecyclerView(recyclerView);

        editPublishLearnVideoItemBottomDialog = EditPublishLearnVideoItemBottomDialog.newInstance();
        editPublishLearnVideoItemBottomDialog.setListener(new EditPublishLearnVideoItemBottomDialog.Listener() {
            @Override
            public void onDelete(int position) {
                publishLearnVideoAdapter.remove(position);
                autoConfigTrail();
                {
                    if (edit) {
                        Map<String, String> attrs = new HashMap<>();
                        attrs.put("action_type", "1");
                        trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_MOD_SUB_VIDEO_ACT, TrackEvent.LEARN_VIDEO_MOD_SUB_VIDEO_ACT_LABEL, attrs, true);
                    }
                }
                if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
                    Map<String, String> attrs = new HashMap<>();
                    attrs.put("action_type", "1");
                    trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_MOD_SUB_ACT_EDIT, TrackEvent.LEARN_VIDEO_MOD_SUB_ACT_EDIT_LABEL, attrs, true);
                }
            }
        });
        publishLearnVideoAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                PublishLearnVideoItem publishLearnVideoItem = publishLearnVideoAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.coverLayout:
                        if (!publishLearnVideoItem.isPreUpload()) {
                            currentPosition = position;
                            {
                                if (edit) {
                                    Map<String, String> attrs = new HashMap<>();
                                    attrs.put("action_type", "2");
                                    trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_MOD_SUB_VIDEO_ACT, TrackEvent.LEARN_VIDEO_MOD_SUB_VIDEO_ACT_LABEL, attrs, true);
                                }
                                if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
                                    Map<String, String> attrs = new HashMap<>();
                                    attrs.put("action_type", "2");
                                    trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_MOD_SUB_ACT_EDIT, TrackEvent.LEARN_VIDEO_MOD_SUB_ACT_EDIT_LABEL, attrs, true);
                                }
                            }
                            ARouter.getInstance().build(ARouterConfig.SelectVideoCoverPage)
                                    .withString("videoUrl", publishLearnVideoItem.getVideoUrl())
                                    .navigation(PublishLearnVideoPage.this, REQUEST_CODE_SELECT_VIDEO_COVER);
                        }
                        break;
                    case R.id.previewBtn: {
                        List<PlayerInfo> playList = new ArrayList<>();
                        playList.add(PlayerInfo.newBuilder()
                                .cover(publishLearnVideoItem.getCoverUrl())
                                .isFree(true)
                                .path(publishLearnVideoItem.getVideoUrl())
                                .title(publishLearnVideoItem.getTitle())
                                .build());
                        trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_PREVIEW, TrackEvent.LEARN_VIDEO_PREVIEW_LABEL);
                        {
                            if (edit) {
                                Map<String, String> attrs = new HashMap<>();
                                attrs.put("action_type", "4");
                                trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_MOD_SUB_VIDEO_ACT, TrackEvent.LEARN_VIDEO_MOD_SUB_VIDEO_ACT_LABEL, attrs, true);
                            }
                        }
                        ARouter.getInstance()
                                .build(ARouterConfig.PlayerPage)
                                .withSerializable("playList", (Serializable) playList)
                                .navigation();
                        break;
                    }
                    case R.id.actionLayout:
                        editPublishLearnVideoItemBottomDialog.setPosition(position);
                        editPublishLearnVideoItemBottomDialog.show(getSupportFragmentManager(), "");
                        break;
                    case R.id.trailBtn:
                        List<PublishLearnVideoItem> itemList = publishLearnVideoAdapter.getData();
                        if (publishLearnVideoItem.isTrail()) {
                            publishLearnVideoItem.setTrail(false);
                            publishLearnVideoAdapter.setData(position, publishLearnVideoItem);
                        } else {
                            for (PublishLearnVideoItem item : itemList) {
                                item.setTrail(false);
                            }
                            publishLearnVideoItem.setTrail(true);
                            publishLearnVideoAdapter.notifyDataSetChanged();
                        }
                        if (position == 0) {
                            Map<String, String> attrs = new HashMap<>();
                            attrs.put("first_trail", "0");
                            trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_TRAIL_FIRST, TrackEvent.LEARN_VIDEO_TRAIL_FIRST_LABEL, attrs);
                        } else {
                            Map<String, String> attrs = new HashMap<>();
                            attrs.put("first_trail", "1");
                            trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_TRAIL_FIRST, TrackEvent.LEARN_VIDEO_TRAIL_FIRST_LABEL, attrs);
                        }
                        if (edit) {
                            Map<String, String> attrs = new HashMap<>();
                            attrs.put("action_type", "4");
                            trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_MOD_SUB_VIDEO_ACT, TrackEvent.LEARN_VIDEO_MOD_SUB_VIDEO_ACT_LABEL, attrs, true);
                        }
                        if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
                            Map<String, String> attrs = new HashMap<>();
                            attrs.put("action_type", "4");
                            trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_MOD_SUB_ACT_EDIT, TrackEvent.LEARN_VIDEO_MOD_SUB_ACT_EDIT_LABEL, attrs, true);
                        }
                        break;
                }
            }
        });
        publishLearnVideoAdapter.setNewData(formModel.getPublishLearnVideoItemList());
        switch (formModel.getOperationType()) {
            case PublishUtil.OPERATION_TYPE_CREATE:
                createAndFirstEnter = true;
                doSelectVideo();
                break;
            default:
                createAndFirstEnter = false;
                break;
        }
    }

    public boolean checkFormValidate() {
        if (ListUtil.isEmpty(publishLearnVideoAdapter.getData())) {
            ToastX.show(R.string.video_can_not_empty);
            return false;
        }

        if (publishLearnVideoAdapter.getData().size() < 2) {
            ToastX.show(R.string.at_least_select_two_video);
            return false;
        }
        boolean emptyTitle = false;
        for (PublishLearnVideoItem item : publishLearnVideoAdapter.getData()) {
            if (TextUtils.isEmpty(item.getTitle())) {
                emptyTitle = true;
                break;
            }
        }
        if (emptyTitle) {
            ToastX.show(R.string.please_add_video_title);
            return false;
        }

        boolean haveTrail = false;
        for (PublishLearnVideoItem item : publishLearnVideoAdapter.getData()) {
            if (item.isTrail()) {
                haveTrail = true;
            }
        }
        if (!haveTrail) {
            ToastX.show(R.string.trail_can_not_empty);
            return false;
        }
        return true;
    }

    public void doSelectVideo() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofVideo())
                .isCamera(false)
                .previewImage(false)
                .previewVideo(false)
                .maxSelectNum(PublishUtil.MAX_PUBLISH_LEARN_VIDEO_NUM)
                .selectionMedia(getSelectedVideo())
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .maxSize(PublishUtil.MAX_PUBLISH_VIDEO_SIZE)
                .forResult(REQUEST_CODE_SELECT_VIDEO);
        {
            if (edit) {
                Map<String, String> attrs = new HashMap<>();
                attrs.put("action_type", "0");
                trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_MOD_SUB_VIDEO_ACT, TrackEvent.LEARN_VIDEO_MOD_SUB_VIDEO_ACT_LABEL, attrs, true);
            }
        }
        if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
            Map<String, String> attrs = new HashMap<>();
            attrs.put("action_type", "0");
            trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.LEARN_VIDEO_MOD_SUB_ACT_EDIT, TrackEvent.LEARN_VIDEO_MOD_SUB_ACT_EDIT_LABEL, attrs, true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_NEXT:
                if (resultCode == RESULT_OK) {
                    setResult(RESULT_OK, data);
                    super.finish();
                } else if (resultCode == RESULT_CANCELED) {
                    edit = true;
                    PublishLearnVideoFormModel tempFormModel = data.getParcelableExtra(PublishLearnVideoFormPage.EXTRA_KEY_FORM_MODEL);
                    if (tempFormModel != null) {
                        formModel = tempFormModel;
                        publishLearnVideoAdapter.setNewData(formModel.getPublishLearnVideoItemList());
                    }
                }
                break;
            case REQUEST_CODE_SELECT_VIDEO_COVER:
                if (resultCode == RESULT_OK) {
                    PublishLearnVideoItem publishLearnVideoItem = publishLearnVideoAdapter.getItem(currentPosition);
                    publishLearnVideoItem.setCoverUrl(data.getStringExtra(SelectVideoCoverPage.EXTRA_KEY_VIDEO_COVER_URL));
                    publishLearnVideoAdapter.setData(currentPosition, publishLearnVideoItem);
                    trackEvent.sendEvent(this, TrackEvent.FIN_SELECT_LEARN_VIDEO_COVER, TrackEvent.FIN_SELECT_LEARN_VIDEO_COVER_LABEL);
                } else {
                    trackEvent.sendEvent(this, TrackEvent.UNSELECT_LEARN_VIDEO_SUB_COVER, TrackEvent.UNSELECT_LEARN_VIDEO_SUB_COVER_LABEL);
                }
                break;
            case REQUEST_CODE_SELECT_VIDEO:
                if (resultCode == RESULT_OK) {
                    createAndFirstEnter = false;
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (!ListUtil.isEmpty(selectList)) {
                        List<PublishLearnVideoItem> publishLearnVideoItemList = new LinkedList<>();
                        for (LocalMedia localMedia : selectList) {
                            publishLearnVideoItemList.add(PublishLearnVideoItem.newBuilder()
                                    .videoUrl(localMedia.getPath())
                                    .duration(localMedia.getDuration())
                                    .size(FileUtil.getFileSize(localMedia.getPath()))
                                    .build());
                        }
                        new AsyncTask<List<PublishLearnVideoItem>, Object, List<PublishLearnVideoItem>>() {
                            LoadingDialog loadingDialog;

                            @Override
                            protected void onPreExecute() {
                                loadingDialog = LoadingDialog.newBuilder()
                                        .with(PublishLearnVideoPage.this)
                                        .message(R.string.text_process)
                                        .show();
                            }

                            @Override
                            protected List<PublishLearnVideoItem> doInBackground(List<PublishLearnVideoItem>... params) {
                                List<PublishLearnVideoItem> itemList = params[0];
                                for (PublishLearnVideoItem item : itemList) {
                                    item.setCoverUrl(VideoUtil.getVideoCover(item.getVideoUrl(), 0));
                                }
                                return itemList;
                            }

                            @Override
                            protected void onPostExecute(List<PublishLearnVideoItem> list) {
                                loadingDialog.dismiss();
                                mergeSelected(list);
                            }
                        }.execute(publishLearnVideoItemList);
                    }
                } else {
                    if (createAndFirstEnter) {
                        super.finish();
                    }
                }
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    public List<LocalMedia> getSelectedVideo() {
        List<LocalMedia> localMediaList = new LinkedList<>();
        List<PublishLearnVideoItem> publishLearnVideoItemList = publishLearnVideoAdapter.getData();
        for (PublishLearnVideoItem item : publishLearnVideoItemList) {
            if (item.isPreUpload()) continue;
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPictureType("video/mp4");
            localMedia.setMimeType(PictureConfig.TYPE_VIDEO);
            localMedia.setPath(item.getVideoUrl());
            localMediaList.add(localMedia);
        }
        return localMediaList;
    }


    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn, R.id.addBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.titleActionBtn:
                if (!checkFormValidate()) {
                    return;
                }

                formModel.setPublishLearnVideoItemList(publishLearnVideoAdapter.getData());
                if (TextUtils.isEmpty(formModel.getCoverUrl()) && !ListUtil.isEmpty(formModel.getPublishLearnVideoItemList())) {
                    formModel.setCoverUrl(formModel.getPublishLearnVideoItemList().get(0).getCoverUrl());
                }
                ARouter.getInstance()
                        .build(ARouterConfig.PublishLearnVideoFormPage)
                        .withParcelable("formModel", formModel)
                        .navigation(this, REQUEST_CODE_NEXT);
                break;
            case R.id.addBtn: {
                doSelectVideo();
                break;
            }
        }
    }

    @Override
    public void finish() {
        if (edit) {
            trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.CANCEL_SELECT_LEARN_VIDEO_EDIT, TrackEvent.CANCEL_SELECT_LEARN_VIDEO_EDIT_LABEL);
        }
        CancelEditDialogUtil.newbuilder(this)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        EventBus.getDefault().post(EventEditLearnVideoFinish.newBuilder()
                                .resultCode(EventEditLearnVideoFinish.RESULT_CANCEL)
                                .build());
                        trackEvent.sendEvent(PublishLearnVideoPage.this, TrackEvent.CANCEL_SELECT_LEARN_VIDEO, TrackEvent.CANCEL_SELECT_LEARN_VIDEO_LABEL);
                        PublishLearnVideoPage.super.finish();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create()
                .show();
    }

    public void mergeSelected(List<PublishLearnVideoItem> selectedItemList) {
        List<PublishLearnVideoItem> currentLearnVideoItemList = publishLearnVideoAdapter.getData();
        Iterator<PublishLearnVideoItem> currentIterator = currentLearnVideoItemList.iterator();
        outerLoop:
        while (currentIterator.hasNext()) {
            PublishLearnVideoItem currentItem = currentIterator.next();
            if (currentItem.isPreUpload()) {
                continue;
            }
            Iterator<PublishLearnVideoItem> selectedIterator = selectedItemList.iterator();
            while (selectedIterator.hasNext()) {
                PublishLearnVideoItem selectedItem = selectedIterator.next();
                if (currentItem.getVideoUrl().equals(selectedItem.getVideoUrl())) {
                    selectedIterator.remove();
                    continue outerLoop;
                }
            }
            currentIterator.remove();
        }
        currentLearnVideoItemList.addAll(selectedItemList);
        autoConfigTrail();
        autoConfigTitle();
        publishLearnVideoAdapter.notifyDataSetChanged();
    }

    public void autoConfigTrail() {
        if (ListUtil.isEmpty(publishLearnVideoAdapter.getData())) return;
        boolean hasTrail = false;
        for (PublishLearnVideoItem item : publishLearnVideoAdapter.getData()) {
            if (item.isTrail()) {
                hasTrail = true;
                break;
            }
        }
        if (!hasTrail) {
            PublishLearnVideoItem item = publishLearnVideoAdapter.getItem(0);
            item.setTrail(true);
            publishLearnVideoAdapter.setData(0, item);
        }
    }

    public void autoConfigTitle() {
//        if (ListUtil.isEmpty(publishLearnVideoAdapter.getData())) return;
//        int upLimit = publishLearnVideoAdapter.getData().size();
//        for (int i = 0; i < upLimit; ++i) {
//            PublishLearnVideoItem item = publishLearnVideoAdapter.getItem(i);
//            if (TextUtils.isEmpty(item.getTitle())) {
//                item.setTitle(String.format(StringUtils.getString(R.string.episode_no), i + 1));
//            }
//        }
    }
}
